package com.example.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiSmartworkHrmEmployeeQuerydimissionRequest;
import com.dingtalk.api.request.OapiSmartworkHrmEmployeeQueryonjobRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.response.OapiSmartworkHrmEmployeeQuerydimissionResponse;
import com.dingtalk.api.response.OapiSmartworkHrmEmployeeQueryonjobResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.example.service.UserService;
import com.example.service.serviceImpl.UserServiceImpl;
import com.taobao.api.ApiException;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserGet extends HttpServlet {

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("/user_exit")
    public void ExitUser(HttpServletRequest request){//获取离职员工
        try {
            HttpSession session = request.getSession();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
            OapiSmartworkHrmEmployeeQuerydimissionRequest req = new OapiSmartworkHrmEmployeeQuerydimissionRequest();
            Long offset=0L;
            req.setOffset(offset);
            req.setSize(25L);
            OapiSmartworkHrmEmployeeQuerydimissionResponse rsp = client.execute(req, session.getAttribute("Token").toString());

            JSONObject object = JSONObject.parseObject(rsp.getBody()).getJSONObject("result");

            //int num = 25+Integer.parseInt(object.getString("next_cursor"));
            while (object.getString("next_cursor")!=null){
                offset = offset+Integer.parseInt(object.getString("next_cursor"));
                req.setOffset(offset);
                rsp = client.execute(req, session.getAttribute("Token").toString());
                object = JSONObject.parseObject(rsp.getBody()).getJSONObject("result");
            }
            System.out.println(offset);
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping("/user_update")
    public void GetUser(HttpServletRequest request) throws Exception{//获取全部实习员工与正式员工

        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
            OapiSmartworkHrmEmployeeQueryonjobRequest req = new OapiSmartworkHrmEmployeeQueryonjobRequest();
            req.setStatusList("3");
            Long offset=0L;
            req.setOffset(offset);
            req.setSize(25L);
            HttpSession session = request.getSession(); //= HttpServletRequest.getSession();
            String token = session.getAttribute("Token").toString();
            OapiSmartworkHrmEmployeeQueryonjobResponse rsp = client.execute(req,token);

            JSONObject object = JSONObject.parseObject(rsp.getBody());
            JSONObject object1 = object.getJSONObject("result");

            JSONArray jsonArray = object1.getJSONArray("data_list");
            //设置一个list来获取所有的uid
            List<Object> uid = new ArrayList<>();
            for (Object jsay:jsonArray){
                uid.add(jsay);
            }
            System.out.println("uid的一部分："+uid+"\n");

            int i=0;//用来计算遍历次数的。可删

            //循环整个钉钉里面的数据，主要判断方式是当next_cursor这个项目不为空或者是0的时候，就代表后面还有数据，所有继续往下读取数据。
            //||Integer.parseInt(object1.getString("next_cursor"))!=0
            while(object1.getString("next_cursor")!=null){
                offset = offset+25L;
                req.setOffset(offset);
                rsp = client.execute(req,token);
                object = JSONObject.parseObject(rsp.getBody());
                object1 = object.getJSONObject("result");
                jsonArray.clear();
                jsonArray = object1.getJSONArray("data_list");
                for (Object jsay:jsonArray){
                    uid.add(jsay);
                }
            }

            //上面获取到了所有人的uid，下面将在钉钉里面找到对应的名字与工号。
            try {
                client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
                OapiV2UserGetRequest request1 = new OapiV2UserGetRequest();
                request1.setLanguage("zh_CN");
                int length=uid.size();
                //遍历钉钉里面的所有人，找到工号后和数据库里面的工号进行查找，有相同的就更新名字，没有就插入。
                int update =0,insert=0;
                System.out.println(length);

//这里是用于单独读取一个员工的工号姓名.
//                int text=1532;
//                request1.setUserid(uid.get(text).toString());
//                OapiV2UserGetResponse rsp2 = client.execute(request1, token);
//
//                JSONObject objectt = JSONObject.parseObject(rsp2.getBody());
//                System.out.println(rsp2.getBody());
//
//                String jobidt = objectt.getJSONObject("result").getString("job_number");
//                String unamet = objectt.getJSONObject("result").getString("name");
//                System.out.println(jobidt+" "+unamet);

                for (int ul=0;ul<length;ul++) {
                    request1.setUserid(uid.get(ul).toString());
                    OapiV2UserGetResponse rsp1 = client.execute(request1, token);

                    JSONObject object2 = JSONObject.parseObject(rsp1.getBody());
                    String jobid = object2.getJSONObject("result").getString("job_number");

                    if (jobid!=null&&!jobid.equals("")) {
                        System.out.println(jobid);
                        String uname = object2.getJSONObject("result").getString("name");

                        if ((userService.hasId(jobid))) {
                            userService.InsertUser(jobid, uname);
                            insert += 1;
                        } else {
                            userService.updateUser(jobid, uname);
                            update += 1;
                        }
                    }
                    System.out.println("jobid:"+jobid+"   length："+ul+"\n插入了"+insert+"条新数据"+" 更新了"+update+"条旧数据");
                }
            } catch (ApiException e) {
                e.printStackTrace();
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }
}
